<%-- 
    Document   : routeFinder
    Created on : Aug 11, 2009, 9:43:43 AM
    Author     : david
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html style="height:100%">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

        <link rel="stylesheet" type="text/css" href="/ext/resources/css/ext-all.css"/>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
        <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAM8o2I5tj16bQKMUb2eWgghTzyIyaiIcyVAbEGxsZymrytUhO-RS_jxXPLwrxa4PlQ_8lIjxxYUWbKw"></script>
        <script type="text/javascript" src="/ext/adapter/ext/ext-base.js"></script>
        <script type="text/javascript" src="/ext/ext-all.js"></script>
        <title>Route Finder</title>

        <script>
            function ById(val) {
                return document.getElementById(val);
            }
            var clm;
            var dlm;
            offset = 0.004;
            Ext.onReady(function(){
                Ext.QuickTips.init();
                // current location marker
                clm = getStartMarker(new GLatLng( 51.487034, -2.6776));
                

                dlm = getEndMarker(new GLatLng( 51.456594, -2.60427));
                GEvent.addListener(dlm, "dragend", function() {
                    //marker.openInfoWindowHtml("New Start Point");
                    //alert("Requestion Load end  stops");
                    loadStops(null, true);
                });
                var mapdiv = ById("map_canvas");
                var useragent = navigator.userAgent;
                
                map = new GMap2(ById("map_canvas"));
                map.addControl(new GSmallMapControl());
                map.addControl(new GMapTypeControl());
                
                start_store = new Ext.data.JsonStore({
                    root: 'stops',
                    totalProperty: 'total',
                    idProperty: 'stopid',
                    remoteSort: true,                 
                    fields: [
                        'stopid', 'name', 'description', 'latitude', 'longitude', 'connected'
                    ],

                    // load using script tags for cross domain, if the data in on the same domain as
                    // this page, an HttpProxy would be better
                    proxy: new Ext.data.HttpProxy({
                        url: 'getStopsNear.jsp'
                    })
                });
                start_store.setDefaultSort('name', 'asc');

                end_store = new Ext.data.JsonStore({
                    root: 'stops',
                    totalProperty: 'total',
                    idProperty: 'stopid',
                    remoteSort: true,
                    fields: [
                        'stopid', 'name', 'description', 'latitude', 'longitude', 'connected'
                    ],

                    // load using script tags for cross domain, if the data in on the same domain as
                    // this page, an HttpProxy would be better
                    proxy: new Ext.data.HttpProxy({
                        url: 'getStopsNear.jsp'
                    })
                });
                end_store.setDefaultSort('name', 'asc');

                function getRouteButton(stopid) {
                    var did = document.getElementById('destination').value;
                    var params = 'drawRoute.jsp?from=' + stopid + '&to=' + did;
                    params += "&startlat=" + clm.getLatLng().lat() + "&endlat=" + dlm.getLatLng().lat();
                    params += "&startlon=" + clm.getLatLng().lng() + "&endlon=" + dlm.getLatLng().lng();
                    return "<br /><button onclick='window.location=\"" + params +  "\"' >Get Route</button>";
                }


                function setDestination(stopid) {
                    return "<br /><button onclick='document.getElementById(\"destination\").value=\"" + stopid + "\"'>Set to destination</button>";
                }

                function setStart(stopid) {
                    return "<br /><button onclick='document.getElementById(\"start\").value=\"" + stopid + "\"'>Set to Start</button>";
                }

                shortestStartDistance = 10000;
                start_store.on('load', function(astore, records, options) {
                    //alert("Loading start Store");
                    if (map) {
                        //map.clearOverlays();
                        
                        for(var i =0; i< records.length; i++) {
                            var field = records[i];
                            //var stopname = field.data.name;
                            var location = new GLatLng(field.data.latitude, field.data.longitude);
                            var marker = createBlueMarker(location, '<b>' + field.data.name + '</b><br />' +field.data.description);
                            if(field.data.connected == 'true') {
                                distance = clm.getLatLng().distanceFrom(marker.getLatLng());
                                //alert(distance +  " " + shortestdistance);
                                if (distance < shortestStartDistance) {
                                    shortestStartDistance = distance;
                                    ById('startid').value = field.data.stopid;
                                }
                                if (field.data.name.toLowerCase().indexOf("rail") > 0) {
                                    marker = createRailMarker(location, '<b>' + field.data.name + '</b><br />' +field.data.description + getRouteButton(field.data.stopid));
                                } else {
                                    marker = createBusMarker(location, '<b>' + field.data.name + '</b><br />' +field.data.description + getRouteButton(field.data.stopid) );
                                }
                                
                            } 
                            map.addOverlay(marker);    
                        }
                        shortestStartDistance = 10000;
                    }

                });

                shortestEndDistance = 10000;
                end_store.on('load', function(astore, records, options) {
                    //alert("loading end store");
                    if (map) {
                        //map.clearOverlays();
                        drawStartEnd();
                        //alert("end store has " + records.length);
                        var lat = Math.abs(dlm.getLatLng().lat());
                        var lng = Math.abs(dlm.getLatLng().lng());
                        for(var i =0; i< records.length; i++) {
                            var field = records[i];
                            //var stopname = field.data.name;
                            var location = new GLatLng(field.data.latitude, field.data.longitude);
                            
                            var marker = createBlueMarker(location, '<b>' + field.data.name + '</b><br />' +field.data.description);

                            
                            if(field.data.connected == 'true') {
                                distance = dlm.getLatLng().distanceFrom(marker.getLatLng());
                                //alert(distance +  " " + shortestdistance);
                                if (distance < shortestEndDistance) {
                                    shortestEndDistance = distance;
                                    document.getElementById('destination').value = field.data.stopid;  
                                }
                                if (field.data.name.toLowerCase().indexOf("rail") > 0) {
                                    marker = createRailMarker(location, '<b>' + field.data.name + '</b><br />' +field.data.description + setDestination(field.data.stopid));
                                } else {
                                    marker = createBusMarker(location, '<b>' + field.data.name + '</b><br />' +field.data.description + setDestination(field.data.stopid));
                                }
                            }
                            map.addOverlay(marker);
                        }
                        shortestEndDistance = 10000;
                    }            
                });

                
                // Creates a marker whose info window displays the letter corresponding
                // to the given index.
                function createBlueMarker(point, title) {
                    var gi = new GIcon(G_DEFAULT_ICON);
                    gi.image = "http://maps.google.com/mapfiles/ms/micons/lightblue.png";
                    gi.shadow ="http://www.google.com/mapfiles/shadow50.png";
                    gi.iconSize = new GSize(18,18);
                    gi.shadowSize = new GSize(18,18);
                    return createMarker(point, title, gi);
                }
                // Creates a marker whose info window displays the letter corresponding
                // to the given index.
                function createRailMarker(point, title) {
                    var gi = new GIcon(G_DEFAULT_ICON);
                    gi.image = "http://maps.google.com/mapfiles/ms/micons/rail.png";
                    gi.shadow ="http://maps.google.com/mapfiles/ms/micons/rail.shadow.png";
                    gi.iconSize = new GSize(24,24);
                    gi.shadowSize = new GSize(24,24);
                    return createMarker(point, title, gi);
                }

                function createBusMarker(point, title) {
                    var gi = new GIcon(G_DEFAULT_ICON);
                    gi.image = "http://maps.google.com/mapfiles/ms/micons/bus.png";
                    gi.shadow ="http://maps.google.com/mapfiles/ms/micons/bus.shadow.png";
                    gi.iconSize = new GSize(24,24);
                    gi.shadowSize = new GSize(24,24);
                    return createMarker(point, title, gi);
                }

                function createMarker(point, title, icon) {
                    var marker = new GMarker(point,{icon: icon});
                    GEvent.addListener(marker, "click", function() {
                        marker.oOverlaypenInfoWindowHtml(title);
                    });
                    return marker;
                }

                function getStartMarker(point) {
                   // alert("called vreatStartMArker");
                    var gi = new GIcon(G_DEFAULT_ICON);
                    gi.image = "http://www.google.com/mapfiles/dd-start.png";
                    gi.shadow ="http://www.google.com/mapfiles/shadow50.png";
                    return createDraggableMarker(point, gi, false, true);
                }

                function getEndMarker(point) {
                    var gi = new GIcon(G_DEFAULT_ICON);
                    gi.image = "http://www.google.com/mapfiles/dd-end.png";
                    gi.shadow ="http://www.google.com/mapfiles/shadow50.png";
                    return createDraggableMarker(point, gi, true, false);
                }
                // Creates a marker whose info window displays the letter corresponding
                // to the given index.
                function createDraggableMarker(point, icon, start, end) {
                   
                    var marker = new GMarker(point, { icon:icon, draggable: true});
                    
                    
                    GEvent.addListener(marker, "dragstart", function() {
                        map.closeInfoWindow();
                    });

                    GEvent.addListener(marker, "click", function() {
                        marker.openInfoWindowHtml(getRouteButton(ById('startid').value) );
                    });
                    return marker;

                }


                function getLocation(){
                    //alert(1);
                    if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(p){
                            clm = getStartMarker(new GLatLng( p.coords.latitude,  p.coords.longitude));
                            GEvent.addListener(clm, "dragend", function() {
                                //marker.openInfoWindowHtml("New Start Point");
                                //alert("Requestion Load start stops");
                                loadStops(true, null);
                            });
                        });
                    }

                }

                function loadStops(start, end) {

                    map.clearOverlays();
                                      
                    if (start) {
                      //  alert("Start Marker moved: getting new Params!")
                        start_store.load({params:{
                                lat: clm.getLatLng().lat(),
                                lon: clm.getLatLng().lng(),
                                offset:offset }
                        });
                        end_store.reload();
                    }
                    if (end) {
                    //    alert("End Marker moved: getting new Params!")
                        end_store.load({params:{
                                lat: dlm.getLatLng().lat(),
                                lon: dlm.getLatLng().lng(),
                                offset:offset}
                        });
                       // alert("End store finished call to load!")
                        start_store.reload();
                    }
                    //end_store.reload();
                    //start_store.reload();
                    drawStartEnd(start == end);
                    
                }
                function drawStartEnd(centered) {
                    //alert(1);
                    map.addOverlay(clm);
                    map.addOverlay(dlm);
                    if (centered) {
                        var cen = new GLatLng(
                        (clm.getLatLng().lat() + dlm.getLatLng().lat()) / 2,
                        (clm.getLatLng().lng() + dlm.getLatLng().lng()) / 2);
                        map.setCenter(cen, 13);
                    }
                }

                

                function ById(val) {
                    return document.getElementById(val);
                }
                getLocation();
                loadStops(true,true);
            });
        </script>
    </head>
    <body style="height:100%; margin:0;">
        <div id="map_canvas" style="width:100%; height:100%"></div>
        <div>
            <form>
                <input type="hidden" id="startid" name="startid">
                <input type="hidden" id="destination" name="destination">
            </form>
        </div>
    </body>

</html>
